<template>
    <view class="tag-selector flex-layout-row gap-col2">
        <view class="u-page__tag-item gap-col-top gap-row-left" style="flex-wrap: wrap" v-for="(item, index) in source" :key="index">
            <view class="tag flex-center" :class="{ selected: item.checked }" @click="handleSelect(index)">
                <text>{{ item.name }}</text>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    name: 'tag-selector',
    props: {
        name: String,
        multiple: Boolean,
        data: Array
    },
    data() {
        return {
            source: []
        };
    },
    mounted() {
        this.source = this.data.map((item) => {
            return {
                value: item.value,
                name: item.text,
                checked: false
            };
        });
    },
    methods: {
        handleSelect(name) {
            if (this.multiple) {
                this.source[name].checked = !this.source[name].checked;
            } else {
                this.source.map((item, index) => {
                    item.checked = index === name ? true : false;
                });
            }
            var data = this.source.filter((a) => a.checked).map((a) => a.value);
            this.$emit('change', this.name, data);
        }
    }
};
</script>

<style lang="scss" scoped>
.tag-selector {
    flex-wrap: wrap;
    .tag {
        background-color: rgb(247, 247, 252);
        border-radius: 4px;
        padding: 4px 6px;
        color: #999;
        &.selected {
            color: #fff;
            background-color: $app-color-primary;
        }
    }
}
</style>
